<template>
  <div class="table-page-search-wrapper">
    <a-form v-if="showFilter" layout="inline">
      <a-row type="flex">
        <a-col :md="5" :sm="7" style="margin-left: 15px">
          <a-form-item label="区域">
            <a-select v-model="queryParam.area" placeholder="请选择区域" @change="dataInit">
              <a-select-option v-for="(i, index) in selectList" :key="index" :value="i.key"
                >{{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-form v-if="!showFilter" layout="inline">
      <a-row type="flex">
        <a-col :md="5" :sm="7" style="margin-left: 15px">
          <a-form-item label="区域">
            {{ queryParam.area }}
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div id="barChart" :style="{ width: '100%', height: height + 'px' }" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { resizePxNum } from '@/utils'
import { getAction } from '@api/manage'
import { USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'

export default {
  name: 'annualTarget',
  components: {
    resizePxNum,
  },
  props: {
    height: {
      type: Number,
      default: 600,
    },
  },
  data() {
    return {
      queryParam: {
        area: '',
      },
      selectList: [
        { name: '黄浦区', key: '黄浦区' },
        { name: '徐汇区', key: '徐汇区' },
        { name: '长宁区', key: '长宁区' },
        { name: '静安区', key: '静安区' },
        { name: '普陀区', key: '普陀区' },
        { name: '虹口区', key: '虹口区' },
        { name: '杨浦区', key: '杨浦区' },
        { name: '闵行区', key: '闵行区' },
        { name: '宝山区', key: '宝山区' },
        { name: '嘉定区', key: '嘉定区' },
        { name: '浦东新区', key: '浦东新区' },
        { name: '金山区', key: '金山区' },
        { name: '松江区', key: '松江区' },
        { name: '青浦区', key: '青浦区' },
        { name: '奉贤区', key: '奉贤区' },
        { name: '崇明区', key: '崇明区' },
      ],
      dataList: [],
      yearList: [],
      lineData: [],
      showFilter: false,
    }
  },
  mounted() {
    let account = Vue.ls.get(USER_INFO).realname
    // 判断account是否包含‘区’这个字
    if (account.includes('区')) {
      this.queryParam.area = account
      this.showFilter = false
    } else {
      this.queryParam.area = '黄浦区'
      this.showFilter = true
    }
    this.dataInit()
  },
  methods: {
    dataInit() {
      this.getData()
      setTimeout(() => {
        this.echartsInit()
      }, 500)
      window.addEventListener('resize', () => {
        this.echartsInit()
      })
    },
    reset() {
      this.queryParam = {}
    },
    echartsInit() {
      let option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.8)', // Tooltip 背景颜色
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
          textStyle: {
            color: '#5B6264',
            fontSize: 14, // 字体大小
          },
          formatter: function (params) {
            let res = params[0].axisValue + '<br/>' // 使用 axisValue 以适应不同类型的坐标轴
            params.forEach(function (item) {
              let value = item.value
              // 根据系列的类型决定是否添加 '%' 后缀
              let valueSuffix = item.seriesType === 'line' ? '%' : ''

              // 判断当前数据是否为同比数据且是否存在值
              if (item.seriesType === 'line' && item.value !== null && item.value !== undefined) {
                res += item.marker + item.seriesName + ': ' + value + valueSuffix + '<br/>'
              } else if (item.seriesType === 'bar') {
                res += item.marker + item.seriesName + ': ' + value + valueSuffix + '<br/>'
              }
            })
            return res
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            // name: '年度',
            data: this.yearList,
            axisTick: {
              alignWithLabel: true,
            },
          },
          //折线X轴
          {
            type: 'category',
            show: false,
            // data: ['1', '2', '3', '4', '5', '6', '7', '8'],
            //刻度线隐藏
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '能源消费总量（万吨标准煤）',
            min: 100,
            // 网格线样式
            splitLine: {
              show: false,
              lineStyle: {
                type: 'solid', //设置网格线类型 dotted：虚线   solid:实线
              },
            },
            axisLabel: {
              fontSize: resizePxNum(11), //字体大小
            },
            nameTextStyle: {
              fontSize: resizePxNum(11), //字体大小
            },
          },
          //折线Y轴
          {
            type: 'value',
            name: '同比（%）',
            // interval: 10,
            axisLabel: {
              formatter: '{value}%',
              fontSize: resizePxNum(11), //字体大小
            },
            nameTextStyle: {
              fontSize: resizePxNum(11), //字体大小
            },
            // 轴线的样式
            axisLine: {
              show: true,
            },
            // 网格线样式
            splitLine: {
              show: false,
              lineStyle: {
                type: 'solid', //设置网格线类型 dotted：虚线   solid:实线
              },
            },
            // 网格线样式
            // splitLine: {
            //   show: true,
            //   lineStyle: {
            //     color: ['#113945'],
            //     width: resizePxNum(1)
            //   }
            // }
          },
        ],
        series: [
          {
            name: '数据值',
            type: 'bar',
            itemStyle: { color: '#198E91' },
            barWidth: resizePxNum(60),
            data: this.dataList,

            label: {
              show: true, //开启显示
              position: 'top', //在上方显示
              textStyle: {
                //数值样式
                // color: 'white',
                color: '#3F4749',
                fontSize: resizePxNum(11),
                // fontSize: 12//字体大小
              },
            },
          },
          {
            name: '同比',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            showSymbol: false,
            symbol: 'circle', //折线点设置：默认为空心，circle为实心点，
            // lineStyle: {
            //   //折线颜色
            //   color: "#A4F19B"
            // },
            itemStyle: {
              normal: {
                color: '#FAC858', //折线点的颜色
                lineStyle: {
                  color: '#FAC858', //折线的颜色
                },
              },
            },
            data: this.lineData,
          },
        ],
      }
      this.myChartOne = echarts.init(document.getElementById('barChart'))
      this.myChartOne.setOption(option)

      window.addEventListener('resize', () => {
        if (this.myChartOne) {
          this.myChartOne.resize()
        }
      })
    },
    getData() {
      getAction('/carbon/carbonOverviewYearData/list', { areaName: this.queryParam.area }).then((res) => {
        console.log(res)
        if (res.result) {
          console.log(res.result.records)
          let rawData = res.result.records
          rawData = rawData.reverse()
          this.yearList = rawData.map((item) => item.year)
          this.dataList = rawData.map((item) => item.totalEnergyConsumption)

          let yoyGrowthRates = []
          for (let i = 1; i < rawData.length; i++) {
            let lastYear = rawData[i - 1].totalEnergyConsumption
            let thisYear = rawData[i].totalEnergyConsumption
            let yoyGrowth = ((thisYear - lastYear) / lastYear) * 100
            yoyGrowthRates.push(yoyGrowth.toFixed(2)) // 保留两位小数
          }
          this.lineData = yoyGrowthRates

          //   在this.lineData的开头插入一个null
          this.lineData.unshift(null)
        }
      })
    },
  },
}
</script>

<style lang="stylus" scoped></style>
